package com.yzt.zhuju.widget.chatroom;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.chatroom.GiftFullScreenAnimRunEvent;
import com.yzt.zhuju.utils.SvgaUtils;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.plugin_widget.RoundImageView;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;

import java.io.IOException;
import java.net.URL;

/**
 * author : bob
 * date   : 2022/12/5
 * desc   :
 */
public class FullScreenAnimView extends FrameLayout {

    public static final String DYNAMICIMAGESVG = "DynamicImageSvg";

    private boolean animIsRunning = false;
    private final Handler handler = new Handler();
    private MediaPlayer mediaPlayer = new MediaPlayer();

    private String specialGiftName;
    private String specialGiftContent;
    private String gifGiftPath;
    private String svgaImage;
    private String svgaConfig;
    private String alphaVideoUrl;

    private RoundImageView ivGifGiftAnim;
    private SVGAImageView svgaImageView;
    private String soundFile;

    public FullScreenAnimView(@NonNull Context context) {
        this(context, null);
    }

    public FullScreenAnimView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FullScreenAnimView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setGiftInfo(String specialGiftName, String specialGiftContent, String gifGiftPath, String svgaImage, String soundFile, String svgaConfig, String alphaVideoUrl) {
        animIsRunning = true;
        this.specialGiftName = specialGiftName;
        this.specialGiftContent = specialGiftContent;
        this.gifGiftPath = gifGiftPath;
        this.svgaImage = svgaImage;
        this.soundFile = soundFile;
        this.svgaConfig = svgaConfig;
        this.alphaVideoUrl = alphaVideoUrl;
        showAnim();
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        return super.onInterceptTouchEvent(e);
    }

    public boolean isAnimIsRunning() {
        return animIsRunning;
    }

    private void showAnim() {
        if (!TextUtils.isEmpty(gifGiftPath)) {
            startGifAnim();
            playMusic();
        } else if (!TextUtils.isEmpty(svgaImage)) {
            startSpecialAnim();
            playMusic();
        } else {
            removeAllViews();
            handler.postDelayed(run, 1000);
        }
    }

    public void playMusic() {
        if (!TextUtils.isEmpty(soundFile)) {
            try {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(soundFile);
                //3 准备播放
                mediaPlayer.prepareAsync();
                mediaPlayer.setLooping(false);
                mediaPlayer.setOnPreparedListener(mediaPlayer -> mediaPlayer.start());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * gif动画
     */
    private void startGifAnim() {
        ivGifGiftAnim = new RoundImageView(getContext());
        ivGifGiftAnim.setScaleType(ImageView.ScaleType.FIT_CENTER);
        LayoutParams layoutParams = new LayoutParams(DisplayUtils.getDisplayPxWidth(), DisplayUtils.getDisplayPxHeight());
        layoutParams.gravity = Gravity.CENTER;
        int viewWidth = DisplayUtils.getDisplayPxWidth() - DisplayUtils.dp2px(20);
        layoutParams.width = viewWidth;
        layoutParams.height = (int) (viewWidth / 750f * 1300);
        ivGifGiftAnim.post(() -> {
            try {
                ImageLoadUtil.loadGifIvOnce(ivGifGiftAnim.getContext(), gifGiftPath, ivGifGiftAnim, new ImageLoadUtil.OnAnimationStatus() {
                    @Override
                    public void onAnimationStart() {

                    }

                    @Override
                    public void onAnimationEnd() {
                        removeAllViews();
                        handler.postDelayed(run, 1000);
                    }
                });
            } catch (Exception e) {
                removeAllViews();
                handler.postDelayed(run, 1000);
            }
        });
        addView(ivGifGiftAnim, layoutParams);
    }

    Runnable run = new Runnable() {
        @Override
        public void run() {
            RxBus.getDefault().post(new GiftFullScreenAnimRunEvent(true));
        }
    };

    @Override
    public void removeAllViews() {
        if (ivGifGiftAnim != null) {
            try {
                ivGifGiftAnim.clearAnimation();
                ivGifGiftAnim.destroyDrawingCache();
            } catch (Exception ignored) {

            }
            ivGifGiftAnim = null;
        }
        if (svgaImageView != null) {
            svgaImageView.isAnimating();
            svgaImageView.stopAnimation();
            svgaImageView = null;
        }
        super.removeAllViews();
        try {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        } catch (Exception ignored) {

        }
        animIsRunning = false;
        System.gc();
    }

    /**
     * SVGA动画
     */
    private void startSpecialAnim() {
        //特殊动画
        if ((!TextUtils.isEmpty(svgaImage) && !"null".equals(svgaImage))) {
            LayoutParams layoutParams = new LayoutParams(DisplayUtils.getDisplayPxWidth(), DisplayUtils.getDisplayPxHeight());
            layoutParams.gravity = Gravity.CENTER;
            addView(initSpecialAnimView(), layoutParams);
        } else {
            removeAllViews();
            handler.postDelayed(run, 1000);
        }
    }

    /**
     * 全屏特殊动画
     */
    private SVGAImageView initSpecialAnimView() {
        svgaImageView = new SVGAImageView(getContext());
        LayoutParams layoutParams = new LayoutParams(DisplayUtils.getDisplayPxWidth(), DisplayUtils.getDisplayPxHeight());
        svgaImageView.setLayoutParams(layoutParams);
        if (TextUtils.equals(specialGiftName, DYNAMICIMAGESVG)) {
            svgaImageView.setLoops(2);
        } else {
            svgaImageView.setLoops(1);
        }
        svgaImageView.setClearsAfterStop(true);
        svgaImageView.setCallback(new SVGACallback() {
            @Override
            public void onStep(int i, double v) {
            }

            @Override
            public void onRepeat() {
            }

            @Override
            public void onFinished() {
                Log.i("fish", "svga:onFinished");
                removeAllViews();
                handler.postDelayed(run, 1000);
            }

            @Override
            public void onPause() {
            }
        });
        if (!TextUtils.isEmpty(svgaImage) && !"null".equals(svgaImage)) {
            if (TextUtils.isEmpty(svgaConfig)) {
                SvgaUtils.loadSvga(svgaImageView, svgaImage);
            } else {
                SVGAParser svgaParser = new SVGAParser(getContext());
                if (!TextUtils.isEmpty(svgaImage) && !"null".equals(svgaImage)) {
                    URL url;
                    try {
                        Log.d("anim_svga_url-全屏礼物", svgaImage);
                        url = new URL(svgaImage);
                        svgaParser.parse(url, getParseCompletion(svgaImageView));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return svgaImageView;
    }

    @NonNull
    private SVGAParser.ParseCompletion getParseCompletion(SVGAImageView svgaImageView) {
        return new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                SVGADynamicEntity svgaDynamicEntity = SvgaUtils.requestDynamicItem(svgaConfig);
                if (null != svgaDynamicEntity) {
                    SVGADrawable drawable = new SVGADrawable(svgaVideoEntity, svgaDynamicEntity);
                    svgaImageView.setImageDrawable(drawable);
                } else {
                    svgaImageView.setVideoItem(svgaVideoEntity);
                }
                svgaImageView.startAnimation();
            }

            @Override
            public void onError() {

            }
        };
    }

    public void clearData() {
        if (handler != null) {
            handler.removeCallbacks(run);
        }
    }
}
